package com.example.rabbitmqdemo.hellorabbitmq.routing;

import cn.hutool.core.util.StrUtil;
import com.example.rabbitmqdemo.hellorabbitmq.CommonUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.concurrent.TimeoutException;

@Slf4j
public class ProducerRouting
{
    static final String ERROR_QUEUE = "queue_error";
    static final String OTHER_QUEUE = "queu_other";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        ConnectionFactory factory = CommonUtil.getFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        String exchangeName = "direct_exchange";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true);
        // 定义 queue
        channel.queueDeclare(ERROR_QUEUE, true, false, false, null);
        channel.queueDeclare(OTHER_QUEUE, true, false, false, null);
        // 绑定
        channel.queueBind(ERROR_QUEUE, exchangeName, "error");
        channel.queueBind(OTHER_QUEUE, exchangeName, "info");
        channel.queueBind(OTHER_QUEUE, exchangeName, "warning");
        //
        sendMsg("error", "error", exchangeName, channel);
        sendMsg("info", "info", exchangeName, channel);
        sendMsg("warning", "warning", exchangeName, channel);
        channel.close();
        connection.close();
    }

    static void sendMsg(String content, String routingKey, String exchangeName, Channel channel) throws IOException {
        String msg = StrUtil.format("{} - {}", content, LocalDateTime.now());
        channel.basicPublish(exchangeName, routingKey, null, msg.getBytes(StandardCharsets.UTF_8));
    }
}
